package com.mask.im.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mask.im.business.common.model.RestResponse;
import com.mask.im.business.mapper.IMFriendRelationMapper;
import com.mask.im.business.model.dto.IMFriendApplicationDTO;
import com.mask.im.business.model.entity.chat.IMFriendApplicationDO;
import com.mask.im.business.model.entity.chat.IMFriendRelationDO;
import com.mask.im.business.model.vo.IMFriendVO;
import com.mask.im.business.service.IMChatListService;
import com.mask.im.business.service.IMFriendApplicationService;
import com.mask.im.business.service.IMFriendRelationService;
import com.mask.token.util.MaskSecurityUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @className：IMFriendRelationServiceImpl
 * @Description: 好友关系接口实现类
 * @Author：jian
 * @Date：2025/9/5 21:33
 */
@Service
public class IMFriendRelationServiceImpl extends ServiceImpl<IMFriendRelationMapper, IMFriendRelationDO> implements IMFriendRelationService {

    @Resource
    private IMFriendApplicationService friendApplicationService;

    @Resource
    private TransactionTemplate transactionTemplate;

    private IMChatListService chatListService;

    @Override
    public Boolean isFriend(Long userId, Long friendId) {
        IMFriendRelationDO imFriendRelation = this.baseMapper.selectOne(new LambdaQueryWrapper<IMFriendRelationDO>().eq(IMFriendRelationDO::getUserId, userId).eq(IMFriendRelationDO::getFriendId, friendId).eq(IMFriendRelationDO::getIsDeleted, Boolean.FALSE));
        return null != imFriendRelation;
    }

    @Override
    public RestResponse<List<IMFriendVO>> getFriendList() {
        Long useLongId = MaskSecurityUtil.getCurrentUserId();
        //获取在线好友列表
        Set<String> onlineList = ChannelServiceImpl.userIdChannel.keySet();
        //查找对应的好友列表
        List<IMFriendVO> friendList = this.baseMapper.getFriendList(useLongId);
        List<IMFriendVO> friendVOList = friendList.stream().peek(item -> {
            Long friendId = item.getFriendId();
            if (onlineList.contains(friendId.toString())) {
                item.setIsOnline(1);
            } else {
                item.setIsOnline(0);
            }
        }).collect(Collectors.toList());
        return RestResponse.ok(friendVOList);
    }

    @Override
    public RestResponse<Void> addFriendApplication(IMFriendApplicationDTO friendApplicationDTO) {
        Long targetUserId = friendApplicationDTO.getTargetUserId();
        if (null != targetUserId) {
            //获取登录信息
            Long userId = MaskSecurityUtil.getCurrentUserId();
            if (userId.equals(targetUserId)) {
                return RestResponse.fail(10002, "您不能添加自己为好友!");
            }
            //校验好友关系是否存在
            IMFriendRelationDO imFriendRelationDO = this.baseMapper.selectOne(new LambdaQueryWrapper<IMFriendRelationDO>()
                    .eq(IMFriendRelationDO::getFriendId, targetUserId)
                    .eq(IMFriendRelationDO::getUserId, userId)
                    .eq(IMFriendRelationDO::getFriendStatus, 1));
            if (null != imFriendRelationDO) {
                return RestResponse.fail(10003, "他已经是您的好友了!");
            }

            //校验是否有申请存在
            IMFriendApplicationDO friendApplicationDO = friendApplicationService.getOne(new LambdaQueryWrapper<IMFriendApplicationDO>()
                    .eq(IMFriendApplicationDO::getApplicantId, userId)
                    .eq(IMFriendApplicationDO::getTargetUserId, targetUserId)
                    .eq(IMFriendApplicationDO::getApplyStatus, 0));
            if (null != friendApplicationDO) {
                return RestResponse.fail(10004, "你有未过期的好友申请!");
            }

            //校验对方是否有未过期好友的申请
            IMFriendApplicationDO friendApplication = friendApplicationService.getOne(new LambdaQueryWrapper<IMFriendApplicationDO>()
                    .eq(IMFriendApplicationDO::getApplicantId, targetUserId)
                    .eq(IMFriendApplicationDO::getTargetUserId, userId)
                    .eq(IMFriendApplicationDO::getApplyStatus, 0));
            //如果存在则直接添加为好友
            if (null != friendApplication) {
                //创建双向好友
                // 双方同时申请，直接建立双向好友关系
                transactionTemplate.execute(status -> {
                    try {
                        // 创建双向好友关系
                        createMutualRelation(userId, targetUserId);
                        // 标记双方申请为已通过
                        friendApplication.setApplyStatus(1); // 1=已通过
                        friendApplication.setHandleTime(LocalDateTime.now());
                        friendApplicationService.updateById(friendApplication);
                        return true;
                    } catch (Exception e) {
                        status.setRollbackOnly();
                        log.error("处理双方同时申请好友失败", e);
                        return false;
                    }
                });
            } else {
                //检查对方是否有你的好友
                IMFriendRelationDO imFriendRelation = this.baseMapper.selectOne(new LambdaQueryWrapper<IMFriendRelationDO>()
                        .eq(IMFriendRelationDO::getFriendId, userId)
                        .eq(IMFriendRelationDO::getUserId, targetUserId)
                        .eq(IMFriendRelationDO::getFriendStatus, 1));
                //存在的话直接创建单项好友
                if (null != imFriendRelation) {
                    //创建单项
                    chatListService.createSingleChatSession(userId, targetUserId);
                }
                //创建新申请
                IMFriendApplicationDO application = new IMFriendApplicationDO();
                application.setApplicantId(userId);
                application.setTargetUserId(targetUserId);
                application.setApplyMessage(Objects.isNull(friendApplicationDTO.getApplyMessage()) ? "" : friendApplicationDTO.getApplyMessage());
                // 待处理
                application.setApplyStatus(0);
                // 7天过期
                application.setExpireTime(LocalDateTime.now().plusDays(7));
                friendApplicationService.save(application);
                //TODO:: 发送消息通知到要添加的好友
            }
            RestResponse.ok();
        }
        return RestResponse.fail(10001, "请选择您要添加的好友!");
    }


    private void handleRequestResponse(Long id) {
        Long userId = MaskSecurityUtil.getCurrentUserId();
        IMFriendApplicationDO friendApplicationDO = friendApplicationService.getById(id);
        //校验请求是否存在
        if (null != friendApplicationDO) {

        } else {
            //好友请求不存在
            return;
        }
        //接收用户id
//        AtomicReference<Boolean> flag = new AtomicReference<>(false);
//        Long receiverId = imReceiveMessage.getReceiverId();
//        Object message = imReceiveMessage.getContent();
//        Long userId = MaskSecurityUtil.getCurrentUserId();
//
//        //保存对方和自己的好友关系（此时的对方为请求者）
////        Friendships serviceOne = friendshipsService.getOne(new LambdaQueryWrapper<Friendships>()
////                .eq(Friendships::getOneUserId, receiverId)
////                .eq(Friendships::getTwoUserId, userId));
//        Friendships serviceOne = new Friendships();
//        //获取前面保存的好友关系（此时还未同意）
////        Friendships friendships = friendshipsService.getOne(new LambdaQueryWrapper<Friendships>()
////                .eq(Friendships::getOneUserId, userId)
////                .eq(Friendships::getTwoUserId, receiverId));
//        Friendships friendships = new Friendships();
//
//        if (friendships == null) {
//            return;
//        }
//
//        //将之前的表示进行确认为好友
//        friendships.setIsFriends(CommonConstant.IS_FRIEND);
//        friendships.setIsDelete(0);
//        friendships.setLatestNews((String) message);
//        friendships.setLatestTime(new Date());
//        Boolean execute = transactionTemplate.execute(status -> {
//            try {
//                //进行刷新好友关系
//                if (Objects.isNull(serviceOne)) {
//                    Friendships receiverFriendships = buildBaseFriendships(receiverId, userId, String.valueOf(message));
//                    receiverFriendships.setLatestNews((String) message);
//                    receiverFriendships.setLatestTime(new Date());
//                    receiverFriendships.setIsFriends(CommonConstant.IS_FRIEND);
////                    friendshipsService.save(receiverFriendships);
//                } else if (serviceOne.getIsDelete().equals(1)) {
//                    serviceOne.setIsDelete(0);
//                    serviceOne.setIsFriends(CommonConstant.IS_FRIEND);
//                    flag.set(true);
////                    friendshipsService.updateById(serviceOne);
//                }
////                friendshipsService.updateById(friendships);
//                return true;
//            } catch (Exception e) {
//                status.setRollbackOnly();
//                return false;
//            }
//        });
//
//        if (BooleanUtil.isTrue(execute)) {
//            //获取添加同意者的信息
//            IMFriendChatMessageDO friendChatMessage = deleteOriginalData(userId, receiverId, (String) message);
//            IMFriendChatMessageDO imFriendChatMessage = deleteOriginalData(receiverId, userId, friendships.getGuestBook());
//            FriendshipsDTO responders = getFriendshipsDTO(userId, receiverId);
//            if (channel != null) {
//                IMSendMessage websocketDTO = new IMSendMessage();
//                websocketDTO.setCmd(WebSocketConstant.ADD_FRIEND_RESPONSE_ADD);
//                websocketDTO.setMessage(responders);
//                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(websocketDTO, SerializerFeature.WriteMapNullValue)));
//            }
//            //获取添加请求者的信息
//            FriendshipsDTO requestor = getFriendshipsDTO(receiverId, userId);
//            Channel requestChannel = channelService.getUserIdChannel(receiverId.toString());
//            if (requestChannel != null && (Objects.isNull(serviceOne) || flag.get())) {
//                IMSendMessage websocketDTO = new IMSendMessage();
//                websocketDTO.setCmd(WebSocketConstant.ADD_FRIEND_RESPONSE_ADD);
//                websocketDTO.setMessage(requestor);
//                requestChannel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(websocketDTO, SerializerFeature.WriteMapNullValue)));
//            } else if (requestChannel != null) {
//                IMSendMessage websocketDTO = new IMSendMessage();
//                FriendChatMessageDTO friendChatMessageDTO1 = new FriendChatMessageDTO();
//                FriendChatMessageDTO friendChatMessageDTO2 = new FriendChatMessageDTO();
//
////                FriendChatMessageDTO friendChatMessageDTO1 = friendshipsService.getChatStorageDTO(friendChatMessage);
////                FriendChatMessageDTO friendChatMessageDTO2 = friendshipsService.getChatStorageDTO(imFriendChatMessage);
//                websocketDTO.setMessage(friendChatMessageDTO1);
//                websocketDTO.setCmd(WebSocketConstant.SINGLE_CHAT);
//                requestChannel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(websocketDTO)));
//            }
//        }
    }

    private void createMutualRelation(Long userIdA, Long userIdB) {
        // 创建 A→B 的关系
        IMFriendRelationDO relationA = new IMFriendRelationDO();
        relationA.setUserId(userIdA);
        relationA.setFriendId(userIdB);
        relationA.setFriendStatus(1);
        this.baseMapper.insert(relationA);

        // 创建 B→A 的关系（双向）
        IMFriendRelationDO relationB = new IMFriendRelationDO();
        relationB.setUserId(userIdB);
        relationB.setFriendId(userIdA);
        relationB.setFriendStatus(1);
        this.baseMapper.insert(relationB);

        // 同步创建双方的单聊会话（chat_list）
        chatListService.createSingleChatSession(userIdA, userIdB);
        chatListService.createSingleChatSession(userIdB, userIdA);

    }
}
